<?php

namespace App\Models;

use App\Services\AlipayService;
use App\Services\StrategyService;
use Illuminate\Auth\Events\Login;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class RiskCredit extends Model
{
    use HasFactory;
    protected $table = 'sp_risk_credit';
    protected $primaryKey = 'id';
    public $timestamps = false;

    const YIDUN_RESULT_DATA =
        [
            'Accept'=>'建议通过',
            'Reject'=>'建议拒绝',
            'Review'=>'建议复议',
            ''=>'无建议'
        ];

    const RISK_CREDIT_OPEN = 1;//百融风控开启
    const RISK_CREDIT_CLOSE = 2;//百融风控关闭

    //测试白名单，不查风控
    const TEST_USER_LIST = [

    ];
    /**
     * 百融风控查询
     * @param $orderId //订单ID
     * @param $alipayUId //支付宝用户ID 2088
     * @param $certName //姓名
     * @param $certNo   //身份证号码
     * @param $mobile   //手机号
     * @return bool
     */
    protected function queryRiskCredit($orderId,$certName,$certNo,$mobile,$member_id){
        $flag = false;
        if($this->where('order_id',$orderId)->count() == 0){
            if(in_array($certNo,self::TEST_USER_LIST)){
                $saveData = [
                    'order_id'=>$orderId,
                    'member_id'=>$member_id,
                    'user_name'=>$certName,
                    'user_idcard'=>$certNo,
                    'user_mobile'=>$mobile,
                    'create_time'=>date('Y-m-d H:i:s')
                ];
                $this->insert($saveData);
                $flag = true;
            }else{
                //请求参数
                $params = [
                    'id'=>$certNo,
                    'cell'=>$mobile,
                    'name'=>$certName
                ];
                //验证流程策略查询
                $verification = StrategyService::make()
                    ->setAction('verification')
                    ->query($params);
                $verification_data = json_decode($verification,true);
                \Illuminate\Support\Facades\Log::debug('验证流程策略:',$verification_data);
                //贷前策略查询
                $strategy = StrategyService::make()
                    ->setAction('strategy')
                    ->query($params);
                $strategy_data = json_decode($strategy,true);
                $saveData = [
                    'order_id'=>$orderId,
                    'member_id'=>$member_id,
                    'user_name'=>$certName,
                    'user_idcard'=>$certNo,
                    'user_mobile'=>$mobile,
                    'create_time'=>date('Y-m-d H:i:s')
                ];

                $report_params['swift_number'] = '';
                if(!empty($verification_data)){
                    $saveData['verification_score'] = $verification_data['InfoVerification']['final_weight'];
                    $saveData['verification_swift_number'] = $verification_data['swift_number'];
                    $saveData['verification_data'] = $verification;
                    $report_params['swift_number'] = $verification_data['swift_number'];
                    $flag = true;
                }

                if(!empty($strategy_data)){
                    $saveData['cheat_score'] = $strategy_data['RiskStrategy']['Rule']['weight'];
                    //$saveData['credit_score'] = $strategy_data['RiskStrategy']['Score']['scoreconsoff'];
                    $saveData['final_decision'] = $strategy_data['RiskStrategy']['final_decision'];
                    $saveData['strategy_swift_number'] = $strategy_data['swift_number'];
                    $saveData['strategy_data'] = $strategy;
                    if(!empty($report_params['swift_number'])){
                        $report_params['swift_number'] = $report_params['swift_number'].','.$strategy_data['swift_number'];
                    }else{
                        $report_params['swift_number'] = $strategy_data['swift_number'];
                    }
                    $flag = true;
                }
                if(!empty($report_params['swift_number'])){
                    $file = StrategyService::make()
                        ->setAction('report_download')
                        ->query($report_params);
//                    Log::debug('风控pdf',[$file]);
                    $fileName = $certNo.date('YmdHis').'.pdf';
                    $path = dirname(dirname(dirname(__FILE__))) . '/storage/tmp/'.$fileName;
                    file_put_contents($path,$file);
                    $uploud_res = AlipayService::upload($fileName,$path);
                    if($uploud_res['status']){
                        if(file_exists($path)){
                            unlink($path);
                        }
                    }
                    $saveData['risk_report_url'] = $fileName;
                }

                //添加记录
                $this->insert($saveData);
            }
        }
        return $flag;
    }

    /**
     * 获取风控信息
     * @param $orderId
     * @return array
     */
    public static function getRiskCredit($orderId){
        $risk = RiskCredit::where(['order_id'=>$orderId])->select('cheat_score','verification_score','final_decision','risk_report_url')->first();
        $risk = obToArray($risk);
        if($risk){
            $risk['final_decision'] = self::YIDUN_RESULT_DATA[$risk['final_decision']];
        }
        return $risk;
    }

    /**
     * 风控查询列表
     */
    public static function getRiskCreditList($page,$pageSize, $where){
        $RiskCredit = RiskCredit::from('sp_risk_credit as rc')
//            ->leftjoin('sp_order_2 as o','o.id','rc.order_id')
            ->leftjoin('sp_shop_user_2 as su','su.member_id','rc.member_id')
            ->select('rc.order_id as trade_no','rc.id','rc.user_name','rc.user_idcard','rc.type','rc.user_mobile','rc.verification_score','rc.cheat_score','rc.final_decision','rc.create_time','rc.risk_report_url','su.shopname')
            ->where($where)
            ->orderBy('rc.id', 'desc')
            ->paginate($pageSize);
        $RiskCredit = obToArray($RiskCredit);
        return $RiskCredit;
    }

    /**
     * 布尔数据查询列表
     */
    public static function getRiskBooleaCreditList($page,$pageSize, $where){
        $RiskCredit = OrderRiskBoolea::from('sp_order_risk_boolea as b')
            ->leftjoin('sp_order_2 as o','b.order_id','=','o.id')
            ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
            ->select('b.*','o.trade_no','o.realname','o.rent_total','o.month_total', 'm.mobile', 'm.cert_name', 'm.cert_no')
            ->where($where)
            ->orderBy('b.order_id', 'desc')
            ->paginate($pageSize);
        $RiskCredit = obToArray($RiskCredit);
        return $RiskCredit;
    }

    /**
     * 雷达报告查询列表
     */
    public static function getRiskRadarCreditList($page,$pageSize, $where){
        $RiskCredit = OrderRadarBoolea::from('sp_order_radar_boolea as b')
            ->leftjoin('sp_order_2 as o','b.order_id','=','o.id')
            ->select('b.*','o.trade_no')
            ->where($where)
            ->orderBy('order_id', 'desc')
            ->paginate($pageSize);
        $RiskCredit = obToArray($RiskCredit);
        return $RiskCredit;
    }


    /**
     * 学历报告查询列表
     */
    public static function getRiskEduCreditList($page,$pageSize, $where){
        $RiskCredit = OrderEDUBoolea::from('sp_order_edu_boolea as b')
            ->leftjoin('sp_order_2 as o','b.order_id','=','o.id')
            ->select('b.*','o.trade_no')
            ->where($where)
            ->orderBy('order_id', 'desc')
            ->paginate($pageSize);
        $RiskCredit = obToArray($RiskCredit);
        return $RiskCredit;
    }

    /**
     * 征信报告查询列表
     */
    public static function getRiskCreCreditList($page,$pageSize, $where){
        $RiskCredit = OrderCredit::from('sp_order_credit as b')
            ->leftjoin('sp_order_2 as o','b.order_id','=','o.id')
            ->select('b.*','o.trade_no')
            ->where($where)
            ->orderBy('order_id', 'desc')
            ->paginate($pageSize);
        $RiskCredit = obToArray($RiskCredit);
        return $RiskCredit;
    }


}
